<template>
  <div class="player">
    <div class="music-container">
      <!-- ../../public/aa.mp3 -->
      <audio
        :src="song.songUrl"
        ref="audio"
      ></audio>
      <!-- 音乐播放列表 -->
      <div
        class="mc-playlists"
        :class="{'mc-playlists-hide':!islistshow}"
      >
        <!-- 播放列表头部 -->
        <div class="mc-playlists-header">
          <div class="playlists-left">
            <span>播放列表</span>
            <span>(共{{songList.length}}首)</span>
          </div>
          <div class="playlists-right">
            <div class="playlists-songer">歌手</div>
            <i
              @click="handlist"
              class="playlists-close iconfont icon-guanbi1"
            ></i>
          </div>
        </div>
        <!-- 播放列表主体歌曲部分 -->
        <div class="mc-playlists-body ps">
          <ol>
            <li
              class="mc-playlists-line"
              v-for="(item,i) in songList"
              :key="i"
              :class="{'active': index==i}"
              @click="choseSong(item,i)"
            >
              <span>{{item.name}}-{{item.album}}</span>
              <span>{{item.artist}}</span>
            </li>
          </ol>
        </div>
      </div>
      <!-- 播放器控件  -->
      <div class="mc-controller">

        <!-- 播放器左侧按钮控件: 上下曲，播放暂停按钮 -->
        <div class="mc-controller-left">
          <div class="mc-cover">
            <img
              :src="song.cover"
              alt="歌手"
            >
          </div>
          <div
            class="mc-button mc-button-skipback"
            @click="skipBack"
          >
            <i class="iconfont icon-zuojiantou"></i>
          </div>
          <div
            class="mc-button mc-button-skippause"
            @click="play"
          >
            <i
              class="iconfont"
              :class="{'icon-zanting':!playing,'icon-bofang':playing}"
            ></i>
          </div>
          <div
            class="mc-button mc-button-skipforword"
            @click="skipForward"
          >
            <i class="iconfont icon-youjiantou"></i>
          </div>
        </div>

        <!-- 播放器中间控件: 进度条，歌曲歌手信息，进度条时间 -->
        <div class="mc-controller-center">
          <!-- 歌手歌曲信息 -->
          <div class="mc-song-msg">
            <div class="mc-songs">
              <span class="mc-songName">{{song.name}}</span>-
              <span class="mc-songer">{{song.artist}}</span>
            </div>
            <span class="mc-time">
              <span class="mc-currentTime">{{currentTime}}</span>/
              <span class="mc-totalTime">{{totalTime}}</span>
            </span>
          </div>
          <!-- 进度条 -->
          <div
            class="mc-progress"
            ref="progressMain"
          >
            <div class="mc-line">
              <!-- mc-currentline 是已经播放的进度 -->
              <div
                class="mc-currentline"
                ref="progressCurrent"
                :style="{'width':widthProgress}"
              ></div>
              <!-- 播放控件按钮 -->
              <div
                class="mc-button"
                ref="progressButton"
                :style="{'left':leftProgress}"
              >
                <!-- <i class="iconfont icon-webicon318"></i> -->
              </div>
            </div>
          </div>
        </div>

        <!-- 播放器右侧控件: 单曲循环播放系列控件，音量，歌单列表控件按钮 -->
        <div class="mc-controller-right">
          <!-- 竖线 -->
          <div class="mc-line">
            <div class="line"></div>
          </div>

          <!-- 音量控件 -->
          <div
            class="mc-volume"
            @click="changeVolumeState"
          >
            <i
              class="iconfont"
              :class="{'icon-yinliang':!ismuted,'icon-A':ismuted}"
            ></i>
          </div>

          <!-- 音量进度条 -->
          <div
            class="mc-volume-line"
            ref="volumeMain"
          >
            <div class="volume-line">
              <div
                class="volume-current"
                ref="volumeCurrent"
                :style="{'width':widthVolume}"
              ></div>
              <div
                class="volume-button"
                ref="volumeButton"
                :style="{'left':leftVolume}"
              ></div>
            </div>
          </div>
          <!-- 循环播放控件 -->
          <div
            class="mc-order"
            @click="chosePlayType"
          >
            <!-- 列表循环 -->
            <i
              v-if="playType == 1"
              class="iconfont icon-xunhuanbofang"
            ></i>
            <!-- 随机播放 -->
            <i
              v-else-if="playType == 2"
              class="iconfont icon-suijibofang"
            ></i>
            <!-- 单曲循环 -->
            <i
              v-else
              class="iconfont icon-danquxunhuan"
            ></i>
          </div>

          <!-- 播放列表控件 -->
          <div
            class="mc-button-playlists"
            @click="handlist"
          >
            <i class="iconfont icon-bofangliebiao"></i>
            <span>{{songList.length}}</span>
          </div>
        </div>
      </div>
      <!-- 提示区 -->
      <div
        class="mc-toast"
        :class="{'mc-toast-hide': error.length<=0}"
      >{{error}}</div>
    </div>
  </div>
</template>

<script>
/*
*  // 请求数据函数
    getData() {
      axios({
        methods: "get",
        url: "https://autumnfish.cn/playlist/detail?id=924680166"
      }).then(res => {
        console.log(res.data.playlist.tracks);
        this.songList = res.data.playlist.tracks;
      });
    },
    getSong(id) {
      axios({
        url: `https://autumnfish.cn/song/url?id=${id}`,
        method: "get"
      }).then((res)=>{
        // console.log(res.data.data,res.data.data[0].url)
        this.url = res.data.data[0].url
        console.log(this.url)
      })
    },
*/
export default {
  data() {
    return {
      // 控制播放列表的显示隐藏
      islistshow: false,
      // 控制audio是否静音
      ismuted: false,
      //进度条比例
      progressScale: 0,
      volumeScale: 0,
      //对象
      fatherVolume: null,
      fatherProgress: null,
      //播放状态
      playing: true,

      // 总的播放时长
      totalTime: "00:00",
      // 当前播放时间
      currentTime: "00:00",
      // 音量
      volume: 1,
      // 播放模式
      playType: 1,
      //当前播放歌曲下标
      index: 0,
      // 报错信息
      error: "",
      // song: {
      //   // 当前播放歌曲信息
      //   id: 1,
      //   name: "",
      //   artist: "",
      //   time: "",
      //   album: "",
      //   cover:
      //     "http://p1.music.126.net/li19i75jz6GGOT79IyAjYA==/109951165100592039.jpg",
      //   songUrl: "",
      // },

      a_songList: [
        // 歌曲列表
        {
          id: 1,
          name: "刚烈女子",
          time: "04:31",
          artist: "锦零",
          album: "?",
          cover:
            "http://p1.music.126.net/li19i75jz6GGOT79IyAjYA==/109951165100592039.jpg",
          songUrl:
            "http://m8.music.126.net/20200708200306/ccb67779f85cbbec5f354e4051f46ab3/ymusic/obj/w5zDlMODwrDDiGjCn8Ky/3068096975/e3d6/07b4/9780/d5bafe48003ed63da02426b2847e5d13.mp3",
        },
      ],
    };
  },
  // 页面加载完毕执行
  created() {
    // console.log(this.songList);
  },

  //进入页面时执行函数
  mounted() {
    //   监听页面是否可见
    this.setPageListen();
    // 获取audio
    this.audio = this.$refs.audio;
    // console.log("mounted");
    this.fatherVolume = this.$refs.volumeMain;
    this.fatherProgress = this.$refs.progressMain;

    // // 播放器音量以及进度条实现 audio 初始化加载以及监听 调用
    this.AchieveControlls();
    this.getData();
    // console.log(this.songList);
  },

  computed: {
    //音量控件参数
    widthVolume() {
      if (this.fatherVolume) {
        // console.log("1");
        return this.$refs.volumeMain.offsetWidth * this.volumeScale + "px";
      } else {
        // console.log("2");
        return 0 + "px";
      }
    },
    leftVolume() {
      if (this.fatherVolume) {
        return this.$refs.volumeMain.offsetWidth * this.volumeScale + "px";
      } else {
        return 0 + "px";
      }
    },
    // 进度条参数
    widthProgress() {
      if (this.fatherProgress) {
        // console.log("3");
        return this.$refs.progressMain.offsetWidth * this.progressScale + "px";
      } else {
        // console.log("4");
        return 0 + "px";
      }
    },
    leftProgress() {
      if (this.fatherProgress) {
        return this.$refs.progressMain.offsetWidth * this.progressScale + "px";
      } else {
        return 0 + "px";
      }
    },
    song() {
      return this.$store.state.song;
    },
    songList() {
      return this.$store.state.songList;
    },
  },
  methods: {
    // 播放器音量以及进度条实现 audio 初始化加载以及监听
    AchieveControlls() {
      // audio 初始化
      this.audioInit();

      //音乐音量进度条
      this.slideFn(
        this.$refs.volumeMain,
        this.$refs.volumeButton,
        this.$refs.volumeCurrent,
        "volumeProgress"
      );
      // 音乐播放进度条
      this.slideFn(
        this.$refs.progressMain,
        this.$refs.progressButton,
        this.$refs.progressCurrent,
        "playProgress"
      );
    },
    // 请求数据函数
    getData() {
      this.axios({
        methods: "get",
        url: "https://autumnfish.cn/playlist/detail?id=924680166",
      })
        .then((res) => {
          // console.log(res.data.playlist.tracks);
          let tracks = res.data.playlist.tracks;
          this.a_songList = res.data.playlist.tracks;
          // console.log(this.songList);

          // 处理数据存储到songList数组中
          // cover
          tracks.forEach((item, i) => {
            this.a_songList[i].cover = item.al.picUrl;
            this.a_songList[i].name = item.name;
            this.a_songList[i].id = item.id;
            this.a_songList[i].time = item.m.size;
            this.a_songList[i].artist = item.ar[0].name;
            this.a_songList[i].album = item.alia[0];
            // this.songList[i].songurl = this.getSong(item.id);
            // this.getSong(this.songList[i].songurl, item.id);
            // console.log(item);
          });
          return tracks;
        })
        .then((tracks) => {
          tracks.forEach((item, i) => {
            this.getSong(item.id).then((res) => {
              // console.log(res.data.data[0].url)
              this.a_songList[i].songUrl = res.data.data[0].url;
            });
          });
          // console.log(tracks);
        })
        .then(() => {
          this.$store.dispatch("a_updateSongList", this.a_songList);
          // this.$store.dispatch("a_updateSong",this.song)
        });
    },
    getSong(id) {
      return this.axios({
        url: `https://autumnfish.cn/song/url?id=${id}`,
        method: "get",
      });
    },
    // 查询数组中的元素并返回索引值
    findValueIndex(array, value) {
      let backValue = -1;
      for (let index in array) {
        if (array[index] == value) {
          backValue = index;
          return backValue;
        }
      }
      return backValue;
    },
    // audio初始化以及后续监听
    insertArray(insertSong) {
      let state_songList = this.$store.state.songList;
      // 查询sessionStorage 会话存储中是否已经有本地播放歌曲的id
      let idArray = JSON.parse(sessionStorage.getItem("SongList_Song__ID"));

      // 查询歌曲是否在播放列表中
      let index = this.findValueIndex(idArray, insertSong.id);
      console.log(index);
      if (index == -1) {
        // 没有找到
        state_songList.unshift(insertSong);
        this.index = 0;
        this.$store.dispatch("a_updateSongList", state_songList);
      }
      // 如果当前歌曲在播放列表第一,不处理
      if (index == 0) {
        return;
      }
      if (index > 0) {
        new Promise((resolve) => {
          state_songList.splice(index, 1);
          this.$store.dispatch("a_updateSongList", state_songList);
          resolve()
        }).then(()=>{
          state_songList.unshift(insertSong)
          this.index = 0
          this.$store.dispatch("a_updateSongList", state_songList);
        });
      }
      // 已经存在播放列表中

      // console.log({
      //   sessionStorage中存储的播放列表ID数组: idArray[0],
      //   当前播放歌曲的ID: insertSong.id,
      //   state_songList,
      //   是否相等: idArray[0] === insertSong.id,
      // });
    },
    audioInit() {
      let _this = this;
      // console.log("audio初始化");

      // 音频或视频文件已经就绪可以开始，在点击播放时触发
      this.audio.addEventListener("play", () => {
        // console.log("play");
        // 传store.state中存储的当前播放歌曲会导致后面添加的会把前面添加的都改变成后面添加的
        // 插入本地存储的就不会出现
        this.insertArray(JSON.parse(sessionStorage.getItem("Song")));
      });

      // 浏览器开始寻找指定的音频或视频
      this.audio.addEventListener("loadstart", () => {
        // console.log("loadstart");

        // 当前音量进度 volume值介于[0,1]
        _this.volumeScale = _this.audio.volume = 0.3;
        // console.log("volume:  " + _this.audio.volume);
      });

      // 音频或视频的时长已改变
      this.audio.addEventListener("durationchange", () => {
        // console.log("durationchange");
        _this.totalTime = _this.timeToString(_this.audio.duration);
        // console.log("duration:  " + _this.totalTime);
      });

      // 播放位置改变时触发[注意:播放和调整指示定位时都会触发]（主要事件）
      this.audio.addEventListener("timeupdate", () => {
        // 当前播放时间
        _this.currentTime = _this.timeToString(_this.audio.currentTime);

        // 总播放时间
        _this.totalTime = _this.timeToString(_this.audio.duration);

        // 当前播放进度百分比
        let precent = _this.audio.currentTime / _this.audio.duration || 0;

        // 当前播放进度
        _this.progressScale = precent.toFixed(3);

        // 当前进度按钮位置
        // _this.thumbTranslateX = (precent * progressL).toFixed(3);
      });

      // 播放结束
      this.audio.addEventListener(
        "ended",
        () => {
          console.log("ended");
          switch (_this.playType) {
            case 1: // 列表循环
              _this.index =
                _this.index + 1 >= _this.songList.length ? 0 : _this.index + 1;
              break;
            case 2: // 随机播放
              _this.index = Math.floor(Math.random() * _this.songList.length);
              break;
            case 3: // 单曲循环
              break;
          }
          _this.song = _this.songList[_this.index];
          // 此处需要一定的延迟让audio的dom结构获取到，额，你们自己意会或者可以试着去掉看bug
          setTimeout(() => {
            this.audio.play();
          }, 100);
        },
        true
      );

      // 在音频或视频加载发生错误时触发
      this.audio.addEventListener("error", () => {
        // console.log("networkState: " + this.audio.networkState);
        // console.log("readyState: " + this.audio.readyState);
        switch (this.audio.networkState) {
          case "0":
            _this.error = "尚未初始化";
            break;
          case "1":
            _this.error = "正在下载数据";
            break;
          case "3":
            _this.error = "未找到资源";
            break;
        }
        this.audio.readyState == "0" && (_this.error = "音频地址错误");
        /*
          if( this.audio.readyState == "0") {
            _this.error = "音频地址错误"
          }
        */
        // console.log(_this.error);
        setTimeout(() => {
          _this.error = "";
        }, 3000);
      });
    },

    // 列表选歌
    choseSong(item, i) {
      this.$store.dispatch("a_updateSong", item);
      // this.song = item;
      this.index = i;
      this.playing = true;
      setTimeout(() => {
        this.audio.play();
        this.playing = false;
      }, 100);
    },

    /*
     * 播放器控件相关函数开始
     */

    // 上一首
    skipBack() {
      this.skipFn("skipBack");
      // console.log("上一曲");
    },

    // 下一首
    skipForward() {
      this.skipFn("skipForward");
      // console.log("下一曲");
    },

    /*
     *
     *
     *
     *
     *
     *
     * 播放器控件相关函数 开始
     *
     *
     *
     *
     *
     *
     *
     *
     */

    /*
     * 封装进度条滑动函数 开始
     * @params
     *     father [object] 滚动条父元素盒子, 用于获取滚动条总的长度设置滚动总时长
     *     thumb [obj]  滚动条滚动按钮, 用于获取按钮当前的位置等信息
     *     track [obj]  滚动条滚动的进度条, 用于获取已经滚动的进度条长度
     */

    // 函数封装区分两个type情况
    slideFn(father, thumb, track, type) {
      // 获取父盒子的宽度，也就是总的进度条宽度
      var totalLength = father.offsetWidth;
      // 保存全局的this对象
      let _this = this;
      let proportion = 0;
      // 鼠标移动 (在进度条范围内移动)
      let nowX = "";
      // 滚动按钮点击事件
      thumb.onmousedown = function (e) {
        var width;
        if (type === "playProgress") {
          // 鼠标按下时如果type类型为playProgress,则停止播放
          _this.audio.pause();
          width = parseInt(_this.widthProgress);
          // 鼠标按下
          // console.log("playProgress 鼠标按下");
          // console.log(width);
        } else if (type === "volumeProgress") {
          // 如果type:volumeProgress, 不处理
          // 进度条播放长度 计算属性
          width = parseInt(_this.widthVolume);
          // 鼠标按下
          // console.log("volumeProgress 鼠标按下");
          // console.log(width);
        }

        // 保存当前的位置
        let oldX = e.clientX;
        father.onmousemove = function (e) {
          nowX = e.clientX;
          //移动的X
          let moveX = nowX - oldX;
          //移动后长度:移动长度 + 原来长度
          let currentX = moveX + width;
          //边界判定
          if (currentX > totalLength) {
            currentX = totalLength;
            // _this.volume = 100
          } else if (currentX < 0) {
            currentX = 0;
          }
          //比例
          proportion = currentX / totalLength;

          // 判断type进行比例复制
          if (type === "playProgress") {
            _this.progressScale = proportion;
            _this.playing = true;
            //进度赋值改变
            _this.audio.currentTime = _this.audio.duration * proportion;
          } else if (type === "volumeProgress") {
            _this.volumeScale = proportion;
            //音量赋值改变
            _this.audio.volume = proportion;
          }
          // 按钮位置改变
          // thumb.style.left = father.offsetWidth * proportion + "px"
          // console.log(currentX);
        };
        // 鼠标弹起
        document.onmouseup = function () {
          // 改变进度条按钮的位置，改变已经播放进度条的长度

          // 清空鼠标移动事件函数
          father.onmousemove = null;
          document.onmouseup = null;
          if (type === "playProgress") {
            // 鼠标按下时如果type类型为playProgress,则停止播放
            _this.audio.play();
            _this.playing = false;
            // console.log("playProgress 鼠标弹起");
          } else if (type === "volumeProgress") {
            // 如果type:volumeProgress, 不处理
            // console.log("volumeProgress 鼠标弹起");
          }
        };
      };
    },

    /*
     * 封装进度条滑动函数 结束
     */

    /*
     * 封装上下曲控件函数
     * @params
     *    type [TYPE? skipBack : skipForward]
     */
    skipFn(type) {
      //判断播放类型
      // 1 => 列表循环 2 => 随机播放 3 => 单曲循环
      switch (this.playType) {
        case 2:
          this.index = Math.floor(Math.random() * this.songList.length);
          break;
        default:
          if (type == "skipBack") {
            this.index - 1 >= 0 ? this.index-- : 0;
          } else {
            this.index =
              this.index + 1 >= this.songList.length
                ? this.songList.length - 1
                : this.index + 1;
          }
          break;
      }
      this.song = this.songList[this.index];
      this.playing = false;
      console.log(this.song.url, this.index);
      setTimeout(() => {
        this.totalTime = "00:00";
        this.audio.play();
      }, 100);
    },

    /*
     *  上下一曲函数封装 结束
     */

    /*
     * 是否静音 开始
     */

    changeVolumeState() {
      this.ismuted = !this.ismuted;
      // 改变音量状态
      this.audio.muted = this.ismuted;
    },

    /*
     * 是否静音 结束
     */

    /*
     * 播放列表显示隐藏控制函数 开始
     */

    handlist() {
      this.islistshow = !this.islistshow;
    },

    /*
     * 播放列表显示隐藏控制函数 结束
     */

    /*
     * 播放与暂停 开始
     */

    play() {
      if (this.playing) {
        // console.log("播放");
        this.playing = !this.playing;
        this.audio.play();
      } else {
        // console.log("暂停");
        this.playing = !this.playing;
        this.audio.pause();
      }
    },

    /*
     * 播放与暂停 结束
     */

    /*
     * 选择播放方式 开始
     */

    chosePlayType() {
      this.playType = this.playType + 1 > 3 ? 1 : this.playType + 1;
    },

    /*
     * 选择播放方式 结束
     */

    /*
     *
     *
     *
     *
     *
     *
     * 播放器控件相关函数 结束
     *
     *
     *
     *
     *
     *
     *
     *
     */

    /*
     * 秒值转字符串函数封装 开始
     */

    timeToString(param) {
      param = parseInt(param);
      let mm = "",
        ss = "";
      if (param >= 0 && param < 60) {
        param < 10 ? (ss = "0" + param) : (ss = param);
        return "00:" + ss;
      } else if (param >= 60 && param < 3600) {
        mm = parseInt(param / 60);
        mm < 10 ? (mm = "0" + mm) : mm;
        param - parseInt(mm * 60) < 10
          ? (ss = "0" + String(param - parseInt(mm * 60)))
          : (ss = param - parseInt(mm * 60));
        return mm + ":" + ss;
      }
    },

    /*
     * 秒值转字符串函数封装 结束
     */

    /*
     * 页面可见性判断函数 开始
     */

    setPageListen() {
      // 页面页面跳转时执行 visibilitychange(页面改变执行)
      function visibilityChangeEvent() {
        if (!document["hidden"]) {
          // 标题改变
          document.title = "被发现了 (*´∇｀*)";
          // this.audio.play();
          // 音乐播放
        } else if (document["hidden"]) {
          document.title = "藏好了 (つд⊂)  ";
          // this.audio.pause();
        }
      }
      document.addEventListener("visibilitychange", visibilityChangeEvent);
    },
  },
};
</script>

<style lang="scss">
</style>